<!-- src/views/MenuView.vue -->
<template>
  <div>
    <h3>菜品列表</h3>
    <ul>
      <li v-for="dish in dishes" :key="dish.dishId">
        {{ dish.dishName }} - ￥{{ dish.price.toFixed(2) }}
        <button @click="onAddDish(dish.dishId)">加入购物车</button>
      </li>
    </ul>
  </div>
</template>

<script setup>
import { ref, onMounted } from 'vue'
import { getDishes } from '@/utils/menu'
import { addToCart, getCart } from '@/utils/cart'

const dishes = ref([])
const cart = ref([])

// 加载菜品
async function fetchDishes() {
  const res = await getDishes()
  if (res.data.code === 0) dishes.value = res.data.data.dishes
}

// 加载购物车，用于更新页面上购物车数量或其他展示
async function fetchCart() {
  const res = await getCart()
  if (res.data.code === 0) cart.value = res.data.data
}

// 将菜品加入购物车
async function onAddDish(dishId) {
  const res = await addToCart(dishId, 1)
  if (res.data.code === 0) {
    // 加入成功，刷新购物车数据
    await fetchCart()
    alert('已加入购物车！当前共 ' + cart.value.length + ' 件')
  } else {
    alert('加入失败：' + res.data.message)
  }
}

onMounted(async () => {
  await fetchDishes()
  await fetchCart()
})
</script>
